package org.jeecg.modules.activiti.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricIdentityLink;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Comment;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.EmptyUtil;
import org.jeecg.modules.activiti.entity.ActZTask;
import org.jeecg.modules.activiti.entity.ActivitiConstant;
import org.jeecg.modules.activiti.entity.Assignee;
import org.jeecg.modules.activiti.entity.HistoricTaskVo;
import org.jeecg.modules.activiti.service.IActZTaskService;
import org.jeecg.modules.activiti.service.Impl.ActBusinessServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: qixin-boot-parent
 * @description: app 待办任务扩展表
 * @author: wujinbiao
 * @create: 2022-02-14 11:15
 **/
@Api(tags="待办任务扩展表")
@RestController
@RequestMapping("app/api/ext/actZTask")
@Slf4j
public class ApiActZTaskController extends JeecgController<ActZTask, IActZTaskService> {
    @Autowired
    private IActZTaskService actZTaskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    ISysBaseAPI sysBaseAPI;
    // 流程业务扩展表
    @Autowired
    private ActBusinessServiceImpl actBusinessService;
    @Autowired
    private TaskService taskService;

    /**
     * 分页列表查询
     *
     * @param nodeState 0待办 1已办
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "待办任务扩展表-分页列表查询")
    @ApiOperation(value="待办任务扩展表-分页列表查询", notes="待办任务扩展表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(
                                   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                   @RequestParam(name="nodeState", required = true) Integer nodeState,
                                   @RequestParam(name="keyword", required = false) String keyword,
                                   HttpServletRequest req) {
        if(nodeState == null){
            return Result.error("nodestate 不能为空！");
        }

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        QueryWrapper<ActZTask> queryWrapper = QueryGenerator.initQueryWrapper(actZTask, new HashMap<>());
        QueryWrapper<ActZTask> queryWrapper = new QueryWrapper<>();
        // 获取当前登录人待办或已办
        queryWrapper.eq("owner_id", user.getId());
        if ( nodeState == 0 ){
            queryWrapper.orderByDesc("receive_time" );
        }else{
            queryWrapper.orderByDesc("audit_time" );
        }
        if(nodeState != null){
            queryWrapper.eq("node_state",nodeState);
        }
        if(StringUtils.isNotBlank(keyword)){
            queryWrapper.like("title",keyword).or().eq("send_id",keyword);
        }
        Page<ActZTask> page = new Page<ActZTask>(pageNo, pageSize);
        IPage<ActZTask> pageList = actZTaskService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    /**
     * 审批历史记录
     *
     * @param procInstId
     * @param req
     * @return
     */
    @ApiOperation(value="待办任务历史表", notes="待办任务历史表")
    @GetMapping(value = "/queryHistoryList")
    public Result<?> queryHistoryList(
            @RequestParam(name="procInstId", required = true) String procInstId,
            HttpServletRequest req) {
        List<HistoricTaskVo> list = new ArrayList<>();

        List<HistoricTaskInstance> taskList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(procInstId).orderByTaskCreateTime().asc().list();

        // 转换vo
        taskList.forEach(e -> {
            HistoricTaskVo htv = new HistoricTaskVo(e);
            List<Assignee> assignees = new ArrayList<>();
            // 关联分配人（委托用户时显示该人）
            if (StrUtil.isNotBlank(htv.getAssignee())) {
                String assignee = sysBaseAPI.getUserById(htv.getAssignee()).getRealname();
                String owner = sysBaseAPI.getUserById(htv.getOwner()).getRealname();
                assignees.add(new Assignee(assignee + "(受" + owner + "委托)", true));
            }
            List<HistoricIdentityLink> identityLinks = historyService.getHistoricIdentityLinksForTask(e.getId());
            // 获取实际审批用户id
            List<String> userIds_b = actBusinessService.findUserIdByTypeAndTaskId(ActivitiConstant.EXECUTOR_TYPE_b, e.getId());
            List<String> userIds_p = actBusinessService.findUserIdByTypeAndTaskId(ActivitiConstant.EXECUTOR_TYPE_p, e.getId());
            for (HistoricIdentityLink hik : identityLinks) {
                // 关联候选用户（分配的候选用户审批人）
                if (ActivitiConstant.EXECUTOR_candidate.equals(hik.getType()) && StrUtil.isNotBlank(hik.getUserId())) {
                    String username = sysBaseAPI.getUserById(hik.getUserId()).getRealname();
                    Assignee assignee = new Assignee(username, false);
                    /*审批过的标记一下，前端标颜色用*/
                    if (CollectionUtil.contains(userIds_b, hik.getUserId()) || CollectionUtil.contains(userIds_p, hik.getUserId())) {
                        assignee.setIsExecutor(true);
                    }
                    assignees.add(assignee);
                }
            }
            htv.setAssignees(assignees);
            // 关联审批意见
            List<Comment> comments = taskService.getTaskComments(htv.getId(), "comment");
            if (comments != null && comments.size() > 0) {
                htv.setComment(comments.get(0).getFullMessage());
            }

            //如果deletereason为审批通过,同时
            String deleteReason = EmptyUtil.checkNull(htv.getDeleteReason());
            String name = EmptyUtil.checkNull(htv.getName());
            if (name.equals("用户提交") && deleteReason.equals("审批通过")) {
                htv.setDeleteReason("提交审批");
            }

            list.add(htv);
        });
        return Result.ok(list);
    }

    /**
     *   添加
     *
     * @param actZTask
     * @return
     */
    @AutoLog(value = "待办任务扩展表-添加")
    @ApiOperation(value="待办任务扩展表-添加", notes="待办任务扩展表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ActZTask actZTask) {
        actZTaskService.save(actZTask);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     *
     * @param actZTask
     * @return
     */
    @AutoLog(value = "待办任务扩展表-编辑")
    @ApiOperation(value="待办任务扩展表-编辑", notes="待办任务扩展表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ActZTask actZTask) {
        actZTaskService.updateById(actZTask);
        return Result.OK("编辑成功!");
    }

    /**
     *   通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "待办任务扩展表-通过id删除")
    @ApiOperation(value="待办任务扩展表-通过id删除", notes="待办任务扩展表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        actZTaskService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     *  批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "待办任务扩展表-批量删除")
    @ApiOperation(value="待办任务扩展表-批量删除", notes="待办任务扩展表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.actZTaskService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "待办任务扩展表-通过id查询")
    @ApiOperation(value="待办任务扩展表-通过id查询", notes="待办任务扩展表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
        ActZTask actZTask = actZTaskService.getById(id);
        if(actZTask==null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(actZTask);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param actZTask
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ActZTask actZTask) {
        return super.exportXls(request, actZTask, ActZTask.class, "待办任务扩展表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ActZTask.class);
    }

}